package com.nuoniu.sibanyun.service.crm.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.crm.CrmLinkman;
import com.nuoniu.sibanyun.entity.crm.CrmLinkmanHistoryRecord;
import com.nuoniu.sibanyun.entity.crm.CrmStrategy;
import com.nuoniu.sibanyun.entity.crm.CrmTouch;
import com.nuoniu.sibanyun.entity.crm.dto.NotTaskingLinkManSearchDto;
import com.nuoniu.sibanyun.entity.dto.CrmLinkmanDto;
import com.nuoniu.sibanyun.entity.dto.CrmLinkmanSaveDto;
import com.nuoniu.sibanyun.mapper.crm.CrmCustomerMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmLinkmanMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmTouchMapper;
import com.nuoniu.sibanyun.service.crm.ICrmLinkmanHistoryRecordService;
import com.nuoniu.sibanyun.service.crm.ICrmLinkmanService;
import com.nuoniu.sibanyun.service.crm.ICrmStrategyService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 客户联系人 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-06-15
 */
@Service
@Log4j2
public class CrmLinkmanServiceImpl extends ServiceImpl<CrmLinkmanMapper, CrmLinkman> implements ICrmLinkmanService {

    @Autowired
    private CrmCustomerMapper crmCustomerMapper;
    @Autowired
    private ICrmLinkmanHistoryRecordService historyRecordService;

    @Override
    public Page<CrmLinkman> listByDto(Page page, CrmLinkmanDto crmLinkmanDto) {
        String keyword = crmLinkmanDto.getKeyWord();
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<CrmLinkman> queryWrapper = new QueryWrapper();
        if(null != crmLinkmanDto.getCustomerId()){
            queryWrapper.eq("crm_id",crmLinkmanDto.getCustomerId());
        }
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.and(wrapper -> wrapper.like("name", keyword).or().like("mobile", keyword).or().like("office_phone",keyword));
        }

        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.eq("status",0);
        page = page(page, queryWrapper);
        return page;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void setKP(Long linkManId, Long crmId) {
        if(null == linkManId || null == crmId)throw new NuoNiuException("参数错误");
        UserInfo userInfo = UserThreadLocal.get();
        baseMapper.setKP(userInfo.getCompanyId(),linkManId,crmId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveLinkman(CrmLinkmanSaveDto linkmanSaveDto) {
        //检查 客户是否被删除
        Integer crmCustomerStatus = crmCustomerMapper.getCrmCustomerStatus(linkmanSaveDto.getCrmId());
        if( null == crmCustomerStatus || 0 != crmCustomerStatus){
            throw new NuoNiuException("客户信息状态异常，请刷新后重试，或者联系管理员");
        }

        LocalDateTime now = LocalDateTime.now();
        UserInfo userInfo = UserThreadLocal.get();
        CrmLinkman linkman = new CrmLinkman();
        BeanUtils.copyProperties(linkmanSaveDto,linkman);
        if(linkman.getId() ==  null) {
            linkman.setCompanyId(userInfo.getCompanyId());
            linkman.setCreateUserId(userInfo.getUserId());
            linkman.setCreateUserName(userInfo.getRealName());
            linkman.setCreateDate(now);
        }else{
            CrmLinkman oldLinkman = this.getById(linkman.getId());
            CrmLinkmanHistoryRecord historyRecord = new CrmLinkmanHistoryRecord();
            BeanUtils.copyProperties(oldLinkman, historyRecord);
            historyRecord.setType(0);
            historyRecord.setId(null);
            historyRecord.setLinkmanId(linkman.getId());
            historyRecord.setOperateUserId(userInfo.getUserId());
            historyRecord.setOperateUserName(userInfo.getRealName());
            historyRecordService.save(historyRecord);
            //获取 客户策略
//            CrmStrategy crmStrategy = crmStrategyService.getStrategyByCode("crm_7", userInfo.getCompanyId());
//            if(StringUtils.isNotBlank(crmStrategy.getAuxiliaryValue())) {
//                String[] userIdArr = crmStrategy.getAuxiliaryValue().split(",");
//                if(Arrays.asList(userIdArr).contains(userInfo.getUserId())) {
//                    linkman.setUpdateUserId(userInfo.getUserId());
//                    linkman.setUpdateUserName(userInfo.getRealName());
//                    linkman.setUpdateDate(now);
//                    this.saveOrUpdate(linkman);
//                    return;
//                }
//            }
//
//            String strategyVal = crmStrategy.getStrategyVal();
//            Integer maxHours = 0;
//            if(StringUtils.isNotBlank(strategyVal)){
//                try {
//                    maxHours = Integer.valueOf(strategyVal);
//                }catch (Exception e){
//                    throw new NuoNiuException("联系人修改策略错误，请联系管理员");
//                }
//            }
//
//            CrmLinkman crmLinkman = this.getById(linkman.getId());
//            LocalDateTime createDate = crmLinkman.getCreateDate();
//            long hours = Duration.between(createDate, LocalDateTime.now()).toHours();
//            if(maxHours > 0 && hours > maxHours){
//                throw new NuoNiuException("联系人信息已经超过" + maxHours + "小时，不能修改");
//            }
        }

        linkman.setUpdateUserId(userInfo.getUserId());
        linkman.setUpdateUserName(userInfo.getRealName());
        linkman.setUpdateDate(now);
        this.saveOrUpdate(linkman);
    }

    @Override
    public CrmLinkman getByName(String name, Long crmId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("name", name);
        wrapper.eq("crm_id", crmId);
        wrapper.last("LIMIT 1");
        return getOne(wrapper);
    }

    @Override
    @Transactional
    public void disable(String ids) {
        UserInfo userInfo = UserThreadLocal.get();
        for(String id : ids.split(",")) {
            CrmLinkman oldLinkman = this.getById(id);
            CrmLinkmanHistoryRecord historyRecord = new CrmLinkmanHistoryRecord();
            BeanUtils.copyProperties(oldLinkman, historyRecord);
            historyRecord.setType(1);
            historyRecord.setId(null);
            historyRecord.setLinkmanId(oldLinkman.getId());
            historyRecord.setOperateUserId(userInfo.getUserId());
            historyRecord.setOperateUserName(userInfo.getRealName());
            historyRecordService.save(historyRecord);
        }
//        CrmStrategy crmStrategy = crmStrategyService.getStrategyByCode("crm_7", userInfo.getCompanyId());
//        String strategyVal = crmStrategy.getStrategyVal();
//        for(String id : ids.split(",")) {
//            List<CrmTouch> touches = touchMapper.getByLinkManId(id);
//            if(touches.size() > 0) {
//                throw new NuoNiuException("已在联系记录中使用");
//            }
//
//            Integer maxHours = 0;
//            if(StringUtils.isNotBlank(strategyVal)){
//                try {
//                    maxHours = Integer.valueOf(strategyVal);
//                }catch (Exception e){
//                    throw new NuoNiuException("联系人删除策略错误，请联系管理员");
//                }
//            }
//
//            CrmLinkman crmLinkman = this.getById(id);
//            LocalDateTime createDate = crmLinkman.getCreateDate();
//            long hours = Duration.between(createDate, LocalDateTime.now()).toHours();
//            if(maxHours > 0 && hours > maxHours){
//                throw new NuoNiuException("联系人信息已经超过" + maxHours + "小时，不能删除");
//            }
//        }

//        QueryWrapper wrapper = new QueryWrapper();
//        String[] split = ids.split(",");
//        wrapper.eq("company_id",userInfo.getCompanyId());
//        wrapper.in("id",split);
//        this.remove(wrapper);

        UpdateWrapper<CrmLinkman> updateWrapper = new UpdateWrapper<>();
        String[] split = ids.split(",");
        updateWrapper.eq("company_id",userInfo.getCompanyId());
        updateWrapper.in("id",split);
        updateWrapper.set("status",1);
        this.update(updateWrapper);
    }

    @Override
    public Page<CrmLinkmanHistoryRecord> pageHistoryList(Page page, Integer crmId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", UserThreadLocal.get().getCompanyId());
        if(crmId != null) {
            wrapper.eq("crm_id", crmId);
        }
        wrapper.orderByDesc("create_date");
        return historyRecordService.page(page, wrapper);
    }

    /**
     * 查询 可以添加任务的 联系人
     * @param notTaskingLinkManSearchDto
     * @return
     */
    @Override
    public Page<CrmLinkman> pageNotTaskingLinkMan(NotTaskingLinkManSearchDto notTaskingLinkManSearchDto) {
        Page<CrmLinkman> page = notTaskingLinkManSearchDto.getPage();
        UserInfo userInfo = UserThreadLocal.get();
        Page<CrmLinkman> crmLinkmanPage = baseMapper.pageNotTaskingLinkMan(page,userInfo.getCompanyId(), userInfo.getUserId(),notTaskingLinkManSearchDto);
        return crmLinkmanPage;
    }

    @Override
    public void updateCallTaskState(UserInfo userInfo,Set<Long> linkManIds, Integer taskId, boolean isTasking) {
        log.info("更新 联系人外呼任务状态，crmIds:{},taskId;{},isTasking:{}", JSON.toJSONString(linkManIds),taskId,isTasking);
        if(linkManIds.size() == 0)return;
        UpdateWrapper<CrmLinkman> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",linkManIds);
        updateWrapper.eq("company_id",userInfo.getCompanyId());
        if(isTasking){
            updateWrapper.set("crm_task_id",taskId);
            updateWrapper.set("is_tasking",1);
            updateWrapper.eq("crm_task_id",0);
            updateWrapper.eq("is_tasking",0);
        }else{
            updateWrapper.set("crm_task_id",0);
            updateWrapper.set("is_tasking",0);
            updateWrapper.eq("crm_task_id",taskId);
            updateWrapper.eq("is_tasking",1);
        }
        this.update(updateWrapper);
    }

    @Override
    public void updateCallTaskStateByCloseTask(UserInfo userInfo,List<Long> taskIds) {
        log.info("清除 联系人外呼任务状态(指定任务)，taskId;{}", JSON.toJSONString(taskIds));
        if(taskIds.size() == 0)return;
        UpdateWrapper<CrmLinkman> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("company_id",userInfo.getCompanyId());
        updateWrapper.set("crm_task_id",0);
        updateWrapper.set("is_tasking",0);
        updateWrapper.in("crm_task_id",taskIds);
//        updateWrapper.eq("is_tasking",1);
        this.update(updateWrapper);

    }

    @Override
    public List<CrmLinkman> listCrmLinkmanMobile(Collection<Number> linkManIds) {
        if(linkManIds.size() == 0)return null;
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<CrmLinkman> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","mobile");
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.in("id",linkManIds);
        List<CrmLinkman> list = list(queryWrapper);
        return list;
    }
}
